<!--
 * @Descripttion: 
 * @version: 
 * @Author: weni09
 * @Date: 2021-04-13 10:36:48
 * @LastEditors: weni09
 * @LastEditTime: 2021-05-10 09:15:39
 * @FilePath: \blogfastapi\frontend_blog\src\components\WangEditor.vue
-->
<template>
       <div class="editor"></div>
</template>

<script>
// 引入 wangEditor
import wangEditor from 'wangeditor'
import hljs from 'highlight.js'

export default {
  name: "editorElem",
  data() {
    return {
      editor: Object,
      editorData: ''
    }
  },
  props: {
     value: {
        type: String,
        default: ''
      },
      height:{
        type:Number,
        default: 300
      },
      excludeMenus:{
        type: Array,
        default: ['video']
      }
  },
  computed:{
  },

  watch: {
    'value'(val) {
      if (val) {
        if (val !== this.editorData) {
          this.setContent(val);
        }
      } else {
        this.setContent(" ");
      }
    },
      'editorData'(val) {
        if (val && val !== this.value) {
          // 编辑器内容发生变化时，告知外部，实现 v-model 双向监听效果
          // console.log(val)
          this.$emit('input', val)
        }
      },
  },

  mounted() {
    const editor = new wangEditor(`.editor`);
   // 配置 onchange 回调函数，将数据同步到 vue 中
    editor.config.onchange = html => {
      this.editorData = html
    };
    // 配置 server 接口地址
    editor.config.uploadImgServer = global.API_URI + 'upload-img'
    // 限制图片大小
    editor.config.uploadImgMaxSize = 1 * 1024 * 1024
    // 限制一次最多能传几张图片
    editor.config.uploadImgMaxLength = 5 // 一次最多上传 5 个图片
    //自定义 header
    // editor.config.uploadImgHeaders = {
    // Authorization: "Bearer " + this.$store.state.auth.token
    // }
    // withCredentials（跨域传递 cookie)
    editor.config.withCredentials = false
    // 自定义 fileName,这里指后端收到的file对象名称
    editor.config.uploadFileName = 'uploadimg'
    //隐藏插入网络图片的功能
    editor.config.showLinkImg = false
    // 忽略粘贴内容中的图片,主要过滤掉外域路径，图片会自动上传回显
    editor.config.pasteIgnoreImg = true
    // 配置alt选项
    editor.config.showLinkImgAlt = true
    // 配置超链接
    editor.config.showLinkImgHref = false
    // 配置菜单栏，设置不需要的菜单
    editor.config.excludeMenus = this.excludeMenus
    // 挂载highlight插件
    editor.highlight = hljs
    // 编辑器text区高度设置
    editor.config.height = this.height;
    // 编辑器堆叠顺序
    editor.config.zIndex = 10;
    // 创建编辑器
    editor.create()
    this.editor = editor
    // console.log(editor.id)
    //获取传递过来的value,没有显示空
    // console.log(this.value,!this.value)
    if (!this.value){
        editor.txt.html('')
    }
    else{
        editor.txt.html(this.value)
    }
  },
  methods: {
    clearData(){
      this.editor.txt.clear()
    },
    setContent(val) {
      this.editor.txt.html(val)
    },

  },
  beforeDestroy() {
    // 销毁编辑器
    this.editor.destroy()
  },
 

}
</script>

<style lang="scss" scoped>
 
</style>
